package com.aispeech.jarpc.op.post.v2;

import com.aispeech.jarpc.TextBin;
import com.aispeech.jarpc.op.AbstractRequest;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@Slf4j
public class OfflineRequest_v2 extends AbstractRequest {
    private final static String REQ_TMPL = "{\"op\":\"%s\",\"cfg\":\"%s\",\"start_param\":\"%s\",\"feed_param\":\"%s\"}";
    private final static ObjectMapper objectMapper = new ObjectMapper();

    private String lang;
    private String mode;
    private String env;
    private List<Align> aligns;
    public OfflineRequest_v2(String lang, String env) {
        this(lang, env, "long");
    }

    public OfflineRequest_v2(String lang, String env, String mode) {
        this.lang = "en".equalsIgnoreCase(lang) ? lang : "cn";
        this.env = env;
        this.mode = mode;

        aligns = new ArrayList<>();
    }

    public void add(int begin, int end, String rec) {
        aligns.add(new Align(begin, end, rec));
    }

    public void add(int begin, int end, String speaker, String rec) {
        aligns.add(new Align(begin, end, speaker.trim(), rec));
    }

    public int size() {
        return aligns.size();
    }

    @Override
    public String OpType() {
        return "post_DOPC";
    }

    @Override
    public String toJson() throws IOException {
        String cfg = String.format("[RES]/%s/txtpost_%s.cfg", lang, mode);
        String s_aligns = objectMapper.writeValueAsString(aligns).replace("\"", "\\\"");

        return String.format(REQ_TMPL, OpType(), cfg, env, s_aligns);
    }

    public TextBin toJsonBin() throws IOException {
        String json = toJson();
        return new TextBin(json, new byte[0]);
    }

    public class Align {
        private int begin;
        private int end;
        private String speaker;
        private String rec;

        public Align(int begin, int end, String rec) {
            this(begin, end, "", rec);
        }

        public Align(int begin, int end, String speaker, String rec) {
            this.begin = begin;
            this.end = end;
            this.speaker = speaker;
            this.rec = rec;
        }

        public int getBegin() {
            return begin;
        }

        public void setBegin(int begin) {
            this.begin = begin;
        }

        public int getEnd() {
            return end;
        }

        public void setEnd(int end) {
            this.end = end;
        }

        public String getSpeaker() {
            return speaker;
        }

        public void setSpeaker(String speaker) {
            this.speaker = speaker;
        }

        public String getRec() {
            return rec;
        }

        public void setRec(String rec) {
            this.rec = rec;
        }
    }
}
